package com.woniuxy.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.commons.model.Result;
import com.woniuxy.controller.form.LoadAddressForm;
import com.woniuxy.controller.form.UpdateAddressForm;
import com.woniuxy.dao.model.AddressInfo;
import com.woniuxy.service.AddressInfoService;
import com.woniuxy.service.dto.AllAddressDto;
import com.woniuxy.service.dto.UserDetailsDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author psy
 * @since 2022-06-28
 */
@RestController
@RequestMapping("/addressInfo")
@Api(tags = "收货地址接口")
public class AddressInfoController {
    @Resource
    private AddressInfoService addressInfoService;

    /**
     * 加载收货地址(分页)
     * @return 返回用户全部收货信息
     */
    @GetMapping("/loadAddress")
    @ApiOperation("加载收货地址")
    public Result loadAddress(LoadAddressForm loadAddressForm){
        UserDetailsDto userDetailsDto=(UserDetailsDto)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long customerId=userDetailsDto.getId();
        loadAddressForm.setCustomerId(customerId);
        Page<AllAddressDto> allAddressDtoPage = addressInfoService.loadAddress(loadAddressForm);
        return Result.success(200,"初始化地址成功",allAddressDtoPage);
    }

    /**
     * 保存地址修改
     * @param updateAddressFormlist 接收前端传过来的地址信息数组
     * @return
     */
    @PostMapping("/updateaddress")
    @ApiOperation("保存修改收货地址信息")
    public Result updateAddress(@RequestBody List<UpdateAddressForm> updateAddressFormlist){
        UserDetailsDto userDetailsDto=(UserDetailsDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long customerId=userDetailsDto.getId();
        //删除用户地址信息
        boolean b = addressInfoService.delAddress(customerId);
        if(null!=updateAddressFormlist){
            for (int i = 0; i < updateAddressFormlist.size(); i++) {
                updateAddressFormlist.get(i).setCustomerId(customerId);
                addressInfoService.updateAddress(updateAddressFormlist.get(i));
            }
        }
        return Result.success(200,"修改地址成功",null);
    }

}

